package cDB

import (
	"github.com/gin-gonic/gin"
	"github.com/go-redis/redis/v8"
	"go.mongodb.org/mongo-driver/mongo"
	"gorm.io/gorm"

	"gitee.com/csingo/cLog"

	"gitee.com/csingo/cDB/drivers"
)

func Client[T DBClient](ctx *gin.Context, name string) T {
	client := container.Get(name)
	if client == nil {
		cLog.WithContext(ctx, map[string]any{
			"source":     "cDB.Client",
			"connection": name,
		}).Panic("connection is not exists")
	}
	switch cli := client.(type) {
	case *gorm.DB:
		client = cli.WithContext(ctx)
	case *redis.Client:
		client = cli.WithContext(ctx)
	case *mongo.Database:
		client = cli
	}

	return client.(T)
}

func AddConnection(ctx *gin.Context, name string, connection drivers.DriverInterface) error {
	var err error
	var connector drivers.ConnectorInterface

	connector, err = connection.NewConnector(name)
	if err != nil {
		cLog.WithContext(ctx, map[string]any{
			"source":     "cDB.AddConnection",
			"name":       name,
			"connection": connection,
			"err":        err.Error(),
		}).Error("数据库连接异常")
		return err
	}

	if container.Is(connector) {
		container.Save(connector)
	}

	return err
}
